package com.ovopark.organize.server.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ovopark.organize.server.controller.MenusController;
import com.ovopark.organize.server.mapper.FranchiseesRegistrationMapper;
import com.ovopark.organize.server.model.entity.*;
import com.ovopark.organize.server.model.query.FranchiseesRegistrationQuery;
import com.ovopark.organize.server.model.vo.*;
import com.ovopark.organize.server.service.*;
import com.ovopark.organize.server.util.CollectionUtil;
import com.ovopark.organize.server.util.CommonUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class FranchiseesRegistrationServiceImpl extends ServiceImpl<FranchiseesRegistrationMapper, FranchiseesRegistration> implements FranchiseesRegistrationService {

    Logger logger = LoggerFactory.getLogger(MenusController.class);
    @Resource
    private FranchiseesRegistrationContentService franchiseesRegistrationContentService;
    @Resource
    private FranchiseesRegistrationFollowService franchiseesRegistrationFollowService;
    @Resource
    private FranchiseesRegistrationAddressService franchiseesRegistrationAddressService;

    @Resource
    private FranchiseesRegistrationFieldService franchiseesRegistrationFieldService;

    @Resource
    private FranchiseesRegistrationPlanService franchiseesRegistratioPlanService;

    @Resource
    private LogsService logsService;
    @Resource
    private UserService userService;

    @Resource
    private FranchiseesRegistrationLogService franchiseesRegistrationLogService;

    @Override
    public void saveOrUpdateVo(FranchiseesRegistrationSaveVo vo, Integer userId,String remoteIp, String platform) {
         Users users = userService.getUsersById(userId);

        Boolean isChange = false;

        List<FranchiseesRegistrationFieldVo> fieldVo = vo.getFieldVo();
        FranchiseesRegistration bean = new FranchiseesRegistration();
        BeanUtils.copyProperties(vo,bean);
        String nkey = "";
        String operation = "";
        if(vo.getId() ==null){
            bean.setCreateId(userId);
            bean.setCreateTime(new Date());
            if(vo.getFollowUser() !=null){
                bean.setDistributionTime(new Date());
            }
            nkey = "operation.addFranchiseesRegistration.description";
            operation = "addFranchiseesRegistration";
        }else {
            FranchiseesRegistration old =  findFranchiseesRegistrationById(vo.getId());
            if(!old.getName().equals(vo.getName())){
                isChange = true;
            }
            if(!old.getMobilePhone().equals(vo.getMobilePhone())){
                isChange = true;
            }
          nkey = "operation.updateFranchiseesRegistration.description";
          operation = "updateFranchiseesRegistration";
        }
       /* if(bean.getFollowUser() !=null){
            // 需要更新 这个人员 对应的  // 下次跟进时间 nextFollowTime  finalFollowTime followType
                             * 	未分配：线索没有跟进人 0
            //            	 * 	待跟进：线索有跟进人，该跟进人没有添加过跟进记录 1
            //            	 * 	跟进中：线索有跟进人，并且该跟进人添加过跟进记录 2
        }*/
        bean = saveOrUpdateBean(bean);
        franchiseesRegistrationContentService.saveOrUpdateByRegistrationId(bean.getId(),fieldVo,userId,bean.getGroupId());
        // 异步 更新 周边报告 关联的 id 对应的 用户名 和 手机号
        if(isChange){
            franchiseesRegistrationAddressService.updateNameByFranchiseesId(bean.getId(),bean.getName(),bean.getMobilePhone());
        }

        if(users.getGroupId() == null){
            users.setGroupId(bean.getGroupId());
        }

        String parameters = users.getShowName()+","+bean.getName()+bean.getMobilePhone();
        logsService.saveLogsByRemoteIp(operation,users, JSONObject.toJSONString(vo),remoteIp,platform,users.getUserName()+"操作："+bean.getId()+":"+bean.getName()+bean.getMobilePhone(),nkey,parameters);
    }

    @Override
    public FranchiseesRegistration saveOrUpdateBean(FranchiseesRegistration bean) {
        if(bean.getId() !=null){
            baseMapper.updateById(bean);
        }else {
            baseMapper.insert(bean);
        }
        return bean;
    }

    @Override
    public IPage<FranchiseesRegistrationVo> getFranchiseesRegistrationByGroupId(FranchiseesRegistrationQuery query) {

        Page<FranchiseesRegistrationVo> page = new Page<>(query.getPageNumber(), query.getPageSize());
        Integer groupId = query.getGroupId();
        IPage<FranchiseesRegistrationVo> result = new Page<>();
        result.setTotal(0);
        List<Integer>  registrationIds = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(query.getFieldIds())){
            // 筛选出 符合条件得 线索id
            registrationIds =   franchiseesRegistrationContentService.getRegistrationIdByQuery(groupId,query.getFieldIds());
            if(CollectionUtil.isEmpty(registrationIds)){
                return result;
            }
        }

        String registrationIdsQuery = "";
        if(CollectionUtil.isNotEmpty(registrationIds)){
           // queryWrapper.in(FranchiseesRegistration::getId,registrationIds);
            registrationIdsQuery = CommonUtil.IntegerToStringSql(registrationIds);
        }

        if(StringUtils.isNotEmpty(query.getSortField())){
            if(query.getSortField().equals("nextFollowTime")){
                query.setSortField("next_follow_time");
            }
            if(query.getSortField().equals("finalFollowTime")){
                query.setSortField("final_follow_time");
            }

        }


        
        IPage<FranchiseesRegistrationVo> list =    baseMapper.selectFranchiseesRegistrationVoPage(page,query,registrationIdsQuery);
        if(query.getAppHomePage()){
             return list;
        }
        if(CollectionUtil.isNotEmpty(list.getRecords())){
            result.setTotal(list.getTotal());
            // 系统字段
            List<FranchiseesRegistrationVo> franchiseesRegistrations = list.getRecords();
            // 加上 自定义字段 目前固定字段
           List<Integer> groupFieldIds = franchiseesRegistrationFieldService.getFieldIdsByGroupId(groupId);

            Map<Integer,FranchiseesRegistrationVo> franchiseesRegistrationMap = new HashMap<>();

            // 固定字段内容 + 自定义内容
            List<Integer> franchiseesIds =  new ArrayList<>();
            for (FranchiseesRegistrationVo reg:franchiseesRegistrations ) {
                franchiseesIds.add(reg.getId());
                FranchiseesRegistrationVo vo = new FranchiseesRegistrationVo();
                BeanUtils.copyProperties(reg,vo);
                franchiseesRegistrationMap.put(reg.getId(),vo);
            }
                //    franchiseesRegistrations.stream().map(FranchiseesRegistration::getId).collect(Collectors.toList());
            String franchiseesList = CommonUtil.IntegerToStringSql(franchiseesIds);
            String fieldList = CommonUtil.IntegerToStringSql(groupFieldIds);
            List<FranchiseesRegistrationContentVo> franchiseesRegistrationVos = baseMapper.getFranchiseesRegistrationContent(franchiseesList,groupId,fieldList);

            // 下次跟进时间

        //    List<SimpleDateVo> nextTime = franchiseesRegistrationFollowService.getNextFranchiseesRegistrationTime(franchiseesIds,groupId);
       /*     Map<Integer,SimpleDateVo> simpleDateVoMap = new HashMap<>();
            if(CollectionUtil.isNotEmpty(nextTime)){
                simpleDateVoMap = nextTime.stream().collect(Collectors.toMap(SimpleDateVo::getId, Function.identity()));
            }*/

            List<FranchiseesRegistrationVo> resultContent = new ArrayList<>();

            if(CollectionUtil.isNotEmpty(franchiseesRegistrationVos)){
                //  根据 固定字段 聚合；
                for (FranchiseesRegistrationContentVo contentVo:franchiseesRegistrationVos ) {
                    Integer franchiseesSystemId = contentVo.getId();
                    //系统字段
                    FranchiseesRegistrationVo registration = franchiseesRegistrationMap.get(franchiseesSystemId);
                    if(registration ==null){
                        registration = new FranchiseesRegistrationVo();
                        BeanUtils.copyProperties(contentVo,registration);
                    }
                    List<FranchiseesRegistrationFieldVo> fieldVo = registration.getFieldVo();
                    if(CollectionUtil.isEmpty(fieldVo)){
                        fieldVo = new ArrayList<>();
                    }
                    //自定义字段
                    FranchiseesRegistrationFieldVo registrationFieldVo = new FranchiseesRegistrationFieldVo();
                    registrationFieldVo.setFieldId(contentVo.getFieldId());
                    registrationFieldVo.setId(contentVo.getContentId());
                    registrationFieldVo.setValue(contentVo.getContent());
                    if(contentVo.getRegistrationFieldSelectId() !=null){
                        registrationFieldVo.setValue(contentVo.getRegistrationFieldSelectIdList());
                        registrationFieldVo.setValueNames(contentVo.getSelectName());
                    }
                    fieldVo.add(registrationFieldVo);
                    registration.setFieldVo(fieldVo);
                    franchiseesRegistrationMap.put(franchiseesSystemId,registration);
                }

            }
        /*    franchiseesRegistrationMap.forEach((k, v)->{
                resultContent.add(v);
            });*/

            for(FranchiseesRegistrationVo vo : franchiseesRegistrations){
                Integer franchiseesId = vo.getId();
                FranchiseesRegistrationVo registrationVo = franchiseesRegistrationMap.get(franchiseesId);
                if(registrationVo !=null){
                    resultContent.add(registrationVo);
                }

            }


           /*
            if(query.getRecycle() !=null && query.getRecycle() ==1){
                // 回收箱
                Collections.sort(resultContent, new Comparator<FranchiseesRegistrationVo>() {
                    @Override
                    public int compare(FranchiseesRegistrationVo vo1,
                                       FranchiseesRegistrationVo vo2) {
                        return vo2.getRecycleTime().compareTo(vo1.getRecycleTime());
                    }
                });

            }else {
                Collections.sort(resultContent, new Comparator<FranchiseesRegistrationVo>() {
                    @Override
                    public int compare(FranchiseesRegistrationVo vo1,
                                       FranchiseesRegistrationVo vo2) {
                        return vo2.getCreateTime().compareTo(vo1.getCreateTime());
                    }
                });
            }
*/

            result.setRecords(resultContent);

        }


        return result;
    }

    @Override
    public FranchiseesRegistrationVo getFranchiseesRegistrationById(Integer registrationId,Boolean isApp,Integer groupId) {

        FranchiseesRegistrationVo vo = null;
        List<FranchiseesRegistrationContentVo> contentVos = baseMapper.getFranchiseesRegistrationById(registrationId,groupId);
        if(CollectionUtil.isNotEmpty(contentVos)){
            vo = new FranchiseesRegistrationVo();
            Map<Integer,List<SimpleVo>> multipleValueMap = new HashMap<>();
            for (FranchiseesRegistrationContentVo content:contentVos ) {
                // 先处理 多选
                  if(content.getRegistrationFieldSelectId() !=null){
                      List<SimpleVo> simpleVos = multipleValueMap.get(content.getFieldId());
                      if(CollectionUtil.isEmpty(simpleVos)){
                          simpleVos = new ArrayList<>();
                      }
                      if(StringUtils.isNotEmpty(content.getSelectName())){
                          SimpleVo simpleVo = new SimpleVo();
                          simpleVo.setId(content.getRegistrationFieldSelectId());
                          simpleVo.setName(content.getSelectName());
                          simpleVos.add(simpleVo);
                          multipleValueMap.put(content.getFieldId(),simpleVos);
                      }

                 }

            }

            List<Integer> fieldIds = new ArrayList<>();

            for (FranchiseesRegistrationContentVo content:contentVos ) {
                 if(vo.getId() ==null){
                   BeanUtils.copyProperties(content,vo);
                 }
                 // 固定字段 处理；
                List<FranchiseesRegistrationFieldVo> fieldVo =  vo.getFieldVo();
                 if(CollectionUtil.isEmpty(fieldVo)){
                     fieldVo = new ArrayList<>();
                   //  fieldVo = setSystemField(content,fieldVo);
                 }
                FranchiseesRegistrationFieldVo registrationFieldVo = new FranchiseesRegistrationFieldVo();
                registrationFieldVo.setValue(content.getContent());
                registrationFieldVo.setFieldId(content.getFieldId());
                registrationFieldVo.setId(content.getContentId());
                registrationFieldVo.setIsOrder(content.getIsOrder());

                if(content.getRegistrationFieldSelectId() !=null){
                    // 多选
                    List<SimpleVo> simpleVos = multipleValueMap.get(content.getFieldId());
                    if(CollectionUtil.isNotEmpty(simpleVos)){
                        registrationFieldVo.setMultipleValue(simpleVos);
                        registrationFieldVo.setIsMultiple(1);
                        List<String> names = simpleVos.stream().map(SimpleVo::getName).collect(Collectors.toList());
                        String valeuNames = StringUtils.join(names,";");
                        registrationFieldVo.setValue(valeuNames);
                        registrationFieldVo.setValueNames(valeuNames);
                    }else {
                        // 是多选 但是 字段不存在
                        continue;
                    }
                    if(fieldIds.contains(content.getFieldId())){
                        continue;
                    }

                }

                fieldIds.add(content.getFieldId());
             /*   if(content.getRegistrationFieldSelectId() !=null){
                    // 多选
                    registrationFieldVo.setValue(content.getRegistrationFieldSelectId().toString());
                }*/

                fieldVo.add(registrationFieldVo);
           /*     if(CollectionUtil.isNotEmpty(fieldVo)){
                    // 排序
                    Collections.sort(fieldVo, new Comparator<FranchiseesRegistrationFieldVo>() {
                        @Override
                        public int compare(FranchiseesRegistrationFieldVo vo1,
                                           FranchiseesRegistrationFieldVo vo2) {
                            return vo1.getIsOrder().compareTo(vo2.getIsOrder());
                        }
                    });
                }*/
                vo.setFieldVo(fieldVo);
                // 如果是 回收站的数据 详情不显示 跟进人
                if(content.getFollowType() !=null && content.getFollowType().intValue() ==FranchiseesRegistration.FLOW_TYPE_RECYCLE){
                    vo.setFollowUser(null);
                    vo.setFollowUserName(null);
                }
            }

            // 跟进次数
            if(isApp){
                Integer number =  franchiseesRegistrationFollowService.getFollowNumByRegistrationId(registrationId);
                Integer palnNumber =  franchiseesRegistratioPlanService.getNumByRegistrationId(registrationId);
                if(number ==null){
                    number = 0;
                }
                vo.setFollowNum(number);
            }

        }

        return vo;
    }

   private List<FranchiseesRegistrationFieldVo> setSystemField(FranchiseesRegistrationContentVo content, List<FranchiseesRegistrationFieldVo> fieldVo) {
        // 获取 系统字段
        List<FranchiseesRegistrationField> systemFields = franchiseesRegistrationFieldService.getFranchiseesRegistrationSystemFieldByGroupId(content.getGroupId());
        if(CollectionUtil.isNotEmpty(systemFields)){
            for (FranchiseesRegistrationField field:systemFields) {
                FranchiseesRegistrationFieldVo fieldVo1 = new FranchiseesRegistrationFieldVo();
                fieldVo1.setFieldId(field.getId());
                fieldVo1.setId(null);
                fieldVo1.setIsOrder(field.getIsOrder());
               switch (field.getSystemName()){
                   case "userName":
                       fieldVo1.setValue(content.getName());
                       break;
                   case "mobilePhone":
                       fieldVo1.setValue(content.getMobilePhone());
                       break;
                   case "intentionLevel":
                       fieldVo1.setValue(content.getIntentionLevel());
                       break;
                   case "franchiseRegion":
                       fieldVo1.setValue(content.getFranchiseRegion());
                       break;
               }
                fieldVo.add(fieldVo1);
            }

        }
        return fieldVo;
    }

    @Override
    public void deletedFranchiseesRegistrationById(Integer registrationId,Integer deleted,Integer userId,String remoteIp, String platform) {

        FranchiseesRegistration registration = baseMapper.selectById(registrationId);
        if(registration !=null){
      /*      if(deleted ==null){
                // 放入 回收箱
                registration.setIsDeleted(1);
            }else {
                // 彻底 删除  需要备份
                baseMapper.deleteById(registrationId);
            }*/
            registration.setIsDeleted(1);
            saveOrUpdateBean(registration);
            Users users = userService.getUsersById(userId);
            List<FranchiseesRegistrationContent> contents = franchiseesRegistrationContentService.getRegistrationContentByRegistrationId(registrationId);
            String description = users.getUserName()+"操作："+registrationId;
            if(CollectionUtil.isNotEmpty(contents)){
                description = description + "content:"+JSONObject.toJSONString(contents);
                // 放入 历史表中
                List<Integer> ids = new ArrayList<>();
                for (FranchiseesRegistrationContent content:contents ) {
                    ids.add(content.getId());
                }
                franchiseesRegistrationContentService.deletedRegistrationContentByIds(ids);

            }

            String parameters = registration.getName()+registration.getMobilePhone();
            logsService.saveLogsByRemoteIp("deletedFranchiseesRegistration",users, JSONObject.toJSONString(registrationId),remoteIp,platform,description,"operation.deletedFranchiseesRegistration.description",users.getShowName()+","+parameters);
        }


    }

    @Override
    public FranchiseesRegistration findFranchiseesRegistrationById(Integer id) {

        return baseMapper.selectById(id);
    }

    @Override
    public List<FranchiseesRegistration> getFranchiseesMobilePhone(Integer id, String mobilePhone, Integer groupId) {
        if(groupId !=null){
            LambdaQueryWrapper<FranchiseesRegistration> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FranchiseesRegistration::getGroupId,groupId);
            queryWrapper.eq(FranchiseesRegistration::getMobilePhone,mobilePhone);
            if(id !=null){
                queryWrapper.ne(FranchiseesRegistration::getId,id);
            }
            queryWrapper.eq(FranchiseesRegistration::getIsDeleted,0);
            return baseMapper.selectList(queryWrapper);
        }
        return new ArrayList<>();
    }

    @Override
    public List<FranchiseesRegistration> getFranchiseesByFollowUser(Integer groupId, List<Integer> ids) {
        LambdaQueryWrapper<FranchiseesRegistration> queryWrapper = new LambdaQueryWrapper<>();
        if(groupId !=null){
            queryWrapper.eq(FranchiseesRegistration::getGroupId,groupId);
        }
        queryWrapper.eq(FranchiseesRegistration::getIsDeleted,0);
        if(CollectionUtil.isNotEmpty(ids)){
            queryWrapper.in(FranchiseesRegistration::getId,ids);
        }
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public void updateFollowUser(Integer curUserId,Integer groupId, List<Integer> ids, Integer userId,Integer followType, Boolean isDistribution,Boolean isCleanDistribution,
                                 Date nextFollowTime,Date finalFollowTime, Boolean isCleanFinalFollowUser, String operatorType, String remoteIp, String platform) {
        if(CollectionUtil.isNotEmpty(ids) &&  groupId !=null){
            // ids 需要 过滤 只能操作 自己有权限的(自己企业的)
            String registrationIds = CommonUtil.IntegerToStringSql(ids);
            baseMapper.updateFollowUser(groupId,registrationIds,userId,followType,isDistribution,isCleanDistribution,nextFollowTime,finalFollowTime,isCleanFinalFollowUser);
            Users users = userService.getUsersById(curUserId);
            String operationUserName = "null" ;
            if(userId !=null){
                Users operationUser = userService.getUsersById(userId);
                if(operationUser !=null){
                    operationUserName = operationUser.getShowName();
                }
            }
            String description = users.getUserName()+"操作 "+"跟进人："+userId+"param:"+JSONObject.toJSONString(ids) ;
            String parameters = "";
            String operation = "franchiseesRegistration";

            if(operatorType.equals("operation.updateAssignOnePersonnel.description")){
                // 单个
                FranchiseesRegistration franchiseesRegistration = findFranchiseesRegistrationById(ids.get(0));
                parameters = users.getShowName();
                if(franchiseesRegistration !=null){
                    parameters = parameters + ","+ franchiseesRegistration.getName()+franchiseesRegistration.getMobilePhone();
                }
                parameters = parameters + ","+operationUserName;
                operation = "updateAssignOnePersonnel";
            }else  if(operatorType.equals("operation.updateAssignPersonnel.description")){
                // 批量
                parameters = users.getShowName()+","+ids.size()+","+operationUserName;
                operation = "updateAssignPersonnel";
            } else if(operatorType.equals("operation.recycleByRegistration.description") || operatorType.equals("operation.updateGiveUp.description")){ {
                FranchiseesRegistration franchiseesRegistration = findFranchiseesRegistrationById(ids.get(0));
                parameters = users.getShowName();
                if(franchiseesRegistration !=null){
                    parameters = parameters + ","+ franchiseesRegistration.getName()+franchiseesRegistration.getMobilePhone();
                }
               }
               if(operatorType.equals("operation.recycleByRegistration.description")){
                   operation = "recycleByRegistration";
               }

                if(operatorType.equals("operation.updateGiveUp.description")){
                    operation = "updateGiveUp";
                }
            }

            Logs log =   logsService.saveLogsByRemoteIp(operation,users, description,remoteIp,platform,users.getUserName()+"操作："+description,operatorType,parameters);

            // 批量 需要 增加 批量日志
            if(operatorType.equals("operation.updateAssignPersonnel.description")){
               List<FranchiseesRegistration> franchiseesRegistrations = getFranchiseesByFollowUser(groupId,ids);
               List<FranchiseesRegistrationLog> logs = new ArrayList<>();
               for (FranchiseesRegistration franchiseesRegistration : franchiseesRegistrations){
                   FranchiseesRegistrationLog franchiseesRegistrationLog = new FranchiseesRegistrationLog();
                     franchiseesRegistrationLog.setFranchiseesId(franchiseesRegistration.getId());
                     franchiseesRegistrationLog.setFranchiseesName(franchiseesRegistration.getName());
                     franchiseesRegistrationLog.setFranchiseesMobilePhone(franchiseesRegistration.getMobilePhone());
                     franchiseesRegistrationLog.setFollowUserId(userId);
                     franchiseesRegistrationLog.setFollowUserName(operationUserName);
                     franchiseesRegistrationLog.setLogId(log.getId());
                     franchiseesRegistrationLog.setGroupId(groupId);
                     franchiseesRegistrationLog.setCreateId(curUserId);
                     logs.add(franchiseesRegistrationLog);
               }
                franchiseesRegistrationLogService.batchSaveLogs(logs);
            }

        }

    }

    @Override
    public List<SimpleStringStringVo> getSimpleFranchisees(Integer groupId) {
        List<SimpleStringStringVo> list = new ArrayList<>();

        List<FranchiseesRegistration> franchiseesRegistrations = getFranchiseesByFollowUser( groupId, new ArrayList<>());
        if(CollectionUtil.isNotEmpty(franchiseesRegistrations)){
            for (FranchiseesRegistration franch:franchiseesRegistrations ) {
                  Integer id = franch.getId();
                  String name = franch.getName();
                  String moiblePhone = franch.getMobilePhone();
                  if(StringUtils.isNotEmpty(moiblePhone)){
                      name = name + "("+moiblePhone+")";
                  }
                SimpleStringStringVo vo = new SimpleStringStringVo();
                  vo.setId(id);
                  vo.setName(name);
                  vo.setKey(moiblePhone);
                 list.add(vo);

            }

        }

        return list;
    }

    @Override
    public FranchiseesRegistration updateFllowUser(Integer id,String operatorType) {
        // 不是保存最新的，是保存 跟进时间最新的
        //1:删除跟进记录 最后跟进时间：拿最新一次跟进记录的跟进时间
        //2:删除跟进计划 下次跟进时间：拿最近一次跟进计划的跟进时间
        //3:跟进记录自动生成跟进计划 最后跟进时间：拿最新一次跟进记录的跟进时间 下次跟进时间：拿最近一次跟进计划的跟进时间
        FranchiseesRegistration franchiseesRegistration = findFranchiseesRegistrationById(id);
        if(franchiseesRegistration !=null){
            List<FranchiseesRegistrationFollow> newFranchiseesRegistrationFollow = new ArrayList<>();
            if(operatorType.equals("删除跟进记录") || operatorType.equals("自动生成跟进计划")){
                newFranchiseesRegistrationFollow = franchiseesRegistrationFollowService.getFollowByRegistrationId(franchiseesRegistration.getId(),0,true);
            }
            List<FranchiseesRegistrationPlan> newFranchiseesRegistrationFollowPlan = new ArrayList<>();
            if(operatorType.equals("删除跟进计划") || operatorType.equals("自动生成跟进计划")){
                newFranchiseesRegistrationFollowPlan = franchiseesRegistratioPlanService.getPlanByRegistrationId(franchiseesRegistration.getId(),true);
            }

           /* List<FranchiseesRegistrationFollow> newFranchiseesRegistrationFollowPlan = new ArrayList<>();
            if(operatorType.equals("删除跟进计划") || operatorType.equals("自动生成跟进计划")){
                newFranchiseesRegistrationFollowPlan = franchiseesRegistrationFollowService.getFollowByRegistrationId(franchiseesRegistration.getId(),1,true);
            }
            */
            if(CollectionUtil.isNotEmpty(newFranchiseesRegistrationFollow) || CollectionUtil.isNotEmpty(newFranchiseesRegistrationFollowPlan)){
                FranchiseesRegistrationFollow registrationFollow = null;
                if(CollectionUtil.isNotEmpty(newFranchiseesRegistrationFollow)){
                    registrationFollow = newFranchiseesRegistrationFollow.get(0);
                }
                //FranchiseesRegistrationFollow registrationFollowPlan = null;
                FranchiseesRegistrationPlan registrationFollowPlan = null;
                if(CollectionUtil.isNotEmpty(newFranchiseesRegistrationFollowPlan)){
                    registrationFollowPlan =  newFranchiseesRegistrationFollowPlan.get(0);
                }

                Boolean isCleanFinalFollowTime = false;
               Boolean isCleanNextFollowTime  = false;
                if((operatorType.equals("删除跟进记录") || operatorType.equals("自动生成跟进计划")) ){
                    if(registrationFollow !=null){
                        franchiseesRegistration.setFinalFollowTime(registrationFollow.getFollowTime());
                    }else if(operatorType.equals("删除跟进记录")) {
                        isCleanFinalFollowTime = true;
                    }
                }
                if((operatorType.equals("删除跟进计划") || operatorType.equals("自动生成跟进计划"))  ){
                    if(registrationFollowPlan !=null){
                        franchiseesRegistration.setNextFollowTime(registrationFollowPlan.getFollowTime());
                    }else if(operatorType.equals("删除跟进计划")) {
                        isCleanNextFollowTime = true;
                    }

                }
                saveOrUpdateBean(franchiseesRegistration);

                if(isCleanFinalFollowTime || isCleanNextFollowTime){
                    baseMapper.clearFollowTime(franchiseesRegistration.getId(),isCleanFinalFollowTime,isCleanNextFollowTime);
                }

            }else {
                // 需要测 是否能清空
                if(operatorType.equals("删除跟进记录")){
                    franchiseesRegistration.setFinalFollowTime(null);
                    baseMapper.clearFollowTime(franchiseesRegistration.getId(),true,false);
                }
                if(operatorType.equals("删除跟进计划")){
                    franchiseesRegistration.setNextFollowTime(null);
                    baseMapper.clearFollowTime(franchiseesRegistration.getId(),false,true);
                }
              //  baseMapper.updateById(franchiseesRegistration);


            }

        }



        return franchiseesRegistration;
    }

    @Override
    public void cleanFollowUser(List<Integer> ids) {
        if(CollectionUtil.isNotEmpty(ids)){
            String registrationIds = CommonUtil.IntegerToStringSql(ids);
            baseMapper.cleanFollowUserByRegistrationIds(registrationIds);
        }
    }

    @Override
    public Map<Integer,SimpleStatusVo> getFranchiseesRegistrationStatus(Integer groupId, List<Integer> ids) {
        LambdaQueryWrapper<FranchiseesRegistration> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FranchiseesRegistration::getGroupId,groupId);
        queryWrapper.eq(FranchiseesRegistration::getIsDeleted,0);
        if(CollectionUtil.isNotEmpty(ids)){
            queryWrapper.in(FranchiseesRegistration::getId,ids);
        }
        List<FranchiseesRegistration> franchiseesRegistrations = baseMapper.selectList(queryWrapper);
        if(CollectionUtil.isNotEmpty(franchiseesRegistrations)){
            Map<Integer,SimpleStatusVo> simpleStatusVos = new HashMap<>();
            for (FranchiseesRegistration franchiseesRegistration:franchiseesRegistrations ) {
                SimpleStatusVo simpleStatusVo = new SimpleStatusVo();
                simpleStatusVo.setId(franchiseesRegistration.getId());
                simpleStatusVo.setName(franchiseesRegistration.getName());
                simpleStatusVo.setStatus(franchiseesRegistration.getFollowType());
                simpleStatusVos.put(franchiseesRegistration.getId(),simpleStatusVo);
            }
            return simpleStatusVos;
        }
        return new HashMap<>();
    }


}
